import React, {FC, Key, useCallback, useContext, useEffect, useMemo, useState} from 'react';
import "./JournalColumnList.less";
import {JournalDetailContext} from "@/pages/JournalPage/JournalDetail/commons/JournalDetailContext";
import classNames from "classnames";
import {useRequest} from "ahooks";
import * as API from "@/services";
import {HxArticleNormalItem} from "@/components/HxArticleItem";
import {Divider, Empty, message, Space, Spin, Tree} from "antd";
import HxIcon from "@/components/HxIcon";
import useAuthedCheck from "@/components/hooks/UseAuthedCheck";
import queryString from "query-string";
import lodash from "lodash";
import {history} from "@@/core/history";
import HxPagination from "@/components/HxPagination";
import {FormattedMessage} from "@@/exports";

interface JournalColumnListProps {
}

/**
 * 过刊栏目 页面
 */
const JournalColumnList: FC<JournalColumnListProps> = (props) => {
  const {journalId} = useContext(JournalDetailContext)
  const [columnType, setColumnType] = useState<"all" | "special">("all")
  const authedCheck = useAuthedCheck();

  //从请求params中获取选中的期
  const selectedColumnId: API.EntityId | undefined = useMemo(() => {
    const {columnId} = queryString.parse(location?.search);
    let ret = lodash.isArray(columnId) ? columnId[0] : columnId;
    if (!columnId) {
      ret = null;
    }
    return ret || undefined;
  }, [location?.search]);

  const columnsReq = useRequest(() => API.queryFrontJournalColumns({
    pageSize: 1000,
    journalId: journalId,
    special: columnType === "special" ? true : undefined,
  }), {
    refreshDeps: [journalId, columnType]
  });

  const articlesReq = useRequest((p) => API.queryFrontArticlesByEs({
    pageSize: 10,
    ...p,
    periodZ: false,
    hotType: "CREATE_TIME",
    columnId: selectedColumnId,
    journalId: journalId,
  }), {
    ready: !!selectedColumnId,
    refreshDeps: [journalId, selectedColumnId],
  });

  const handleColumnIdSelected = useCallback((columnId: API.EntityId | undefined) => {
    history.push({
      pathname: ``,
      search: queryString.stringify({
        ...queryString.parse(location.search),
        columnId: columnId,
      })
    });
  }, [location.search]);


  const articles = articlesReq.data?.data || [];
  const columns = columnsReq.data?.data || [];

  const treeItems = useMemo(() => {
    return columns.map(c => {
      return {
        key: `${c.id}`,
        title: `${c.name}`,
        selectable: true,
        isLeaf: true,
        icon: (
          <a onClick={(e) => {
            e.preventDefault();
            e.stopPropagation();
            authedCheck(() => {
              API.fav("column", c!.id, !!c?.hascollection, journalId).then(resp => {
                if (resp.flag) {
                  message.success(!c?.hascollection ? "收藏成功":"已取消收藏");
                  columnsReq.mutate((oldData) => {
                    return {
                      ...oldData,
                      data: oldData!.data.map((item) => {
                        if (item.id === c!.id) {
                          return {
                            ...item,
                            hascollection: !item.hascollection,
                          }
                        }
                        return item;
                      })
                    } as API.RespPageResult<API.FrontJournalColumn>;
                  })
                }
              })
            })

          }}>
            <HxIcon type={!!c?.hascollection ? "hxicon-shoucang-yishoucang" : "hxicon-shoucang"}/>
          </a>
        ),
      }
    })
  }, [columns]);

  useEffect(() => {
    if (!selectedColumnId && columns?.length > 0) {
      handleColumnIdSelected(columns[0].id);
    }
  }, [columns]);


  return (
    <div className={"journal-column-list-container"}>
      <div className={"journal-column-tree-wrapper"}>
        <div className={"journal-column-tree-tabs"}>
          <Space split={<Divider type="vertical"/>} size={6}>
            <a className={classNames("journal-column-tree-tab", {"active": columnType === "all"})} onClick={(e) => {
              e.preventDefault();
              setColumnType("all");
            }}>  <FormattedMessage id="text.all"/></a>
            <a className={classNames("journal-column-tree-tab", {"active": columnType === "special"})} onClick={(e) => {
              e.preventDefault();
              setColumnType("special");
            }}>  <FormattedMessage id="journal.featured-column"/></a>
          </Space>
        </div>
        <Tree
          onSelect={(keys) => {
            handleColumnIdSelected(keys.length === 0 ? undefined : keys[0] as string)
          }}
          selectedKeys={selectedColumnId ? [selectedColumnId] : []}
          showIcon={true}
          //icon={<HxIcon type={"hxicon-dot"} style={{color: "#F08C4D"}}/>}
          treeData={treeItems}
        />
      </div>
      <div className={classNames("journal-column-article-list", {"journal-column-article-list-empty": articles.length === 0})}>
        <Spin spinning={articlesReq.loading}>
          {
            articles.length > 0 ? (
                articles?.map((item, index) => (
                  <HxArticleNormalItem key={item.id} showCover={true} article={item} onArticleChange={(article) => {
                    articlesReq?.mutate((oldData) => {
                      return {
                        ...oldData,
                        data: oldData!.data.map((item) => {
                          if (item.id === article.id) {
                            return {
                              ...article,
                            }
                          }
                          return item;
                        })
                      } as API.RespPageResult<API.FrontArticle>;
                    })
                  }}/>
                ))
              )
              :
              <Empty/>
          }
          {
            articlesReq.data && (
              <div className={"hx-pagination-wrapper"}>
                <HxPagination size="default"
                              total={articlesReq.data?.total}
                              current={articlesReq.data.current}
                              pageSize={articlesReq.data.pageSize}
                              onChange={(pageNum, pageSize) => {
                                articlesReq.run({
                                  page: pageNum,
                                  pageSize
                                })
                              }}
                />
              </div>
            )
          }
        </Spin>
      </div>
    </div>
  );
};

export default JournalColumnList;
